package com.lbt.weixin.server.common;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import weixin.popular.client.HttpClientFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lbt.framework.exception.MyException;

public abstract class LbtUtil {

	private static Logger log = LoggerFactory.getLogger(LbtUtil.class);
	
	public static HttpUriRequest getApiRequest(String p, String path) throws MyException {
		String partyCode = CommonConfig.getInstance().getLbtPartyCode();
		String key = CommonConfig.getInstance().getLbtKey();

		String timestamp = String.valueOf(System.currentTimeMillis());
		String sign = CommonUtil.md5Encode(timestamp + partyCode + key + path);
		
		StringBuffer url = new StringBuffer("http://xmlbt.gnway.cc:922/api/user/v1/");//xmautoinfo.com xmlbt.gnway.cc
		url.append(path);
		url.append("?timestamp=");
		url.append(timestamp);
		url.append("&partyCode=");
		url.append(partyCode);
		url.append("&sign=");
		url.append(sign);
		url.append("&p=");
		try {
			url.append(URLEncoder.encode(p, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		HttpUriRequest apiRequest = null;
		apiRequest = RequestBuilder.post()
				.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
				.setUri(url.toString())
				.build();
		
		return apiRequest;
	}

	public static String getApiResult(String p, String path) throws MyException {
		return getApiResult(getApiRequest(p, path));
	}
	
	public static String getApiResult(HttpUriRequest apiRequest) throws MyException {
		String result = null;
		int statusCode = 0;
		try (CloseableHttpClient httpClient = HttpClientFactory.createHttpClient(100, 10, 3000, 0);
				CloseableHttpResponse apiResponse = httpClient.execute(apiRequest)) {
			statusCode = apiResponse.getStatusLine().getStatusCode();
			if (statusCode >= 200 && statusCode < 300) {
				result = EntityUtils.toString(apiResponse.getEntity(), "UTF-8");
			}
		} catch (ConnectTimeoutException e) {
			throw new MyException("网络异常，请稍后再试");
		} catch (HttpHostConnectException e) {
			throw new MyException("网络异常，请稍后再试");
		} catch (Exception e) {
			log.error("力必拓接口请求失败：", e);
			throw new MyException(e);
		} 
		if (null == result) {
			throw new MyException("" + statusCode);
		}
		LbtStatus status = getApiResultCode(result);
		if (200 != status.getCode()) {
			throw new MyException(status.getCode(), status.getDesc());
		}
		return result;
	}
	
	public static LbtStatus getApiResultCode(String apiResult) {
		LbtStatus status = null;
		ObjectMapper om = (ObjectMapper)WebContextFactoryUtil.getBean("objectMapper");
		try {
			status = om.readValue(apiResult, LbtStatus.class);
		} catch (Exception e) {
			log.error("json解析失败：", e);
			throw new MyException(e.getMessage());
		}

		return status;
	}
	
	public static class LbtStatus {
		private String desc;
		private int code;
		public String getDesc() {
			return desc;
		}
		public void setDesc(String desc) {
			this.desc = desc;
		}
		public int getCode() {
			return code;
		}
		public void setCode(int code) {
			this.code = code;
		}
	}
}
